/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmBaoCao.java
 *
 * Created on Dec 10, 2011, 8:42:31 AM
 */
package uit.qlks.from;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.WebRowSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import uit.ejb.dto.BaoCaoThangDTO;
import uit.ejb.dto.CTBaoCaoThangDTO;
import uit.qlks.baocao.BaoCao;
import uit.qlks.controller.baocaothang.BaoCaoThangController;
import uit.qlks.controller.ctbaocaothang.CTBaoCaoThangController;
import uit.qlks.controller.hoadon.HoaDonController;
import uit.qlks.controller.loaiphong.LoaiPhongCotroller;
import uit.qlks.controller.phieuthue.PhieuThueController;
import uit.qlks.controller.phong.PhongController;

/**
 *
 * @author Restart
 */
public class frmBaoCao extends javax.swing.JFrame {

    private long TongTien = 0, _TongTien = 0;
    private long TienDV = 0, _TienDV = 0;
    private String MaBC = null;
    private int i = 1;
    /** Creates new form frmBaoCao */
    public frmBaoCao() {
        initComponents();
        this.lbDoanhThuTemp.setVisible(false);
        this.lbTienDVTemp.setVisible(false);
        this.lbTienPhongTemp.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        ycNam = new com.toedter.calendar.JYearChooser();
        mcThang = new com.toedter.calendar.JMonthChooser();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtDoanhThuLoaiPhong = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        lbTienPhong = new javax.swing.JLabel();
        lbTienDV = new javax.swing.JLabel();
        lbDoanhThu = new javax.swing.JLabel();
        btnLapBaoCao = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        btnXoa = new javax.swing.JButton();
        btnBCThang = new javax.swing.JButton();
        btnBCNam = new javax.swing.JButton();
        lbTienPhongTemp = new javax.swing.JLabel();
        lbDoanhThuTemp = new javax.swing.JLabel();
        lbTienDVTemp = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Báo Cáo Doanh Thu");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Chọn Tháng/Năm"));

        ycNam.setBorder(javax.swing.BorderFactory.createCompoundBorder());

        mcThang.setOpaque(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mcThang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ycNam, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(mcThang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ycNam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Chi tiết báo cáo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14))); // NOI18N

        jtDoanhThuLoaiPhong.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Mã Loại Phòng", "Tên Loại Phòng", "Tiền Phòng", "Tiền DV", "Doanh Thu", "Tỷ Lệ (%)"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtDoanhThuLoaiPhong.setEnabled(false);
        jtDoanhThuLoaiPhong.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jtDoanhThuLoaiPhong);
        jtDoanhThuLoaiPhong.getColumnModel().getColumn(0).setPreferredWidth(0);
        jtDoanhThuLoaiPhong.getColumnModel().getColumn(1).setPreferredWidth(0);
        jtDoanhThuLoaiPhong.getColumnModel().getColumn(2).setPreferredWidth(0);
        jtDoanhThuLoaiPhong.getColumnModel().getColumn(6).setPreferredWidth(0);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 984, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Doanh thu", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14))); // NOI18N
        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setText("Tiền Phòng:");
        jPanel5.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(35, 32, -1, -1));

        jLabel3.setText("Tiền Dịch Vụ:");
        jPanel5.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 32, -1, -1));

        jLabel1.setText("Doanh Thu:");
        jPanel5.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 32, -1, -1));

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jPanel5.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 22, -1, 30));

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jPanel5.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 22, -1, 30));

        lbTienPhong.setText(".......");
        jPanel5.add(lbTienPhong, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 32, -1, -1));

        lbTienDV.setText("......");
        jPanel5.add(lbTienDV, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 32, -1, -1));

        lbDoanhThu.setText("......");
        jPanel5.add(lbDoanhThu, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 32, -1, -1));

        btnLapBaoCao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/bill.png"))); // NOI18N
        btnLapBaoCao.setText("Lập báo cáo");
        btnLapBaoCao.setBorder(null);
        btnLapBaoCao.setContentAreaFilled(false);
        btnLapBaoCao.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/bill2.png"))); // NOI18N
        btnLapBaoCao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLapBaoCaoActionPerformed(evt);
            }
        });

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Printer.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setBorder(null);
        btnPrint.setContentAreaFilled(false);
        btnPrint.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Printer2.png"))); // NOI18N
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });

        btnXoa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete.png"))); // NOI18N
        btnXoa.setText("Xóa");
        btnXoa.setBorder(null);
        btnXoa.setContentAreaFilled(false);
        btnXoa.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete2.png"))); // NOI18N
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnBCThang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/month.png"))); // NOI18N
        btnBCThang.setText("Báo Tháng");
        btnBCThang.setBorder(null);
        btnBCThang.setContentAreaFilled(false);
        btnBCThang.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/month2.png"))); // NOI18N
        btnBCThang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBCThangActionPerformed(evt);
            }
        });

        btnBCNam.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/year.png"))); // NOI18N
        btnBCNam.setText("Báo Cáo Năm");
        btnBCNam.setBorder(null);
        btnBCNam.setContentAreaFilled(false);
        btnBCNam.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/year2.png"))); // NOI18N
        btnBCNam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBCNamActionPerformed(evt);
            }
        });

        lbTienPhongTemp.setText("jLabel4");

        lbDoanhThuTemp.setText("jLabel4");

        lbTienDVTemp.setText("jLabel4");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(329, 329, 329)
                                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(100, 100, 100)
                                .addComponent(btnBCThang)
                                .addGap(34, 34, 34)
                                .addComponent(btnBCNam))
                            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 1016, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnXoa)
                                .addGap(106, 106, 106)
                                .addComponent(btnLapBaoCao)
                                .addGap(102, 102, 102)
                                .addComponent(btnPrint)
                                .addGap(336, 336, 336))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(lbTienPhongTemp)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbDoanhThuTemp)
                        .addGap(18, 18, 18)
                        .addComponent(lbTienDVTemp)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(28, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnBCThang)
                            .addComponent(btnBCNam))
                        .addGap(26, 26, 26)))
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnPrint)
                            .addComponent(btnXoa)
                            .addComponent(btnLapBaoCao))
                        .addContainerGap(27, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lbTienPhongTemp)
                            .addComponent(lbDoanhThuTemp)
                            .addComponent(lbTienDVTemp))
                        .addContainerGap())))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-1072)/2, (screenSize.height-582)/2, 1072, 582);
    }// </editor-fold>//GEN-END:initComponents

      private void DocBaoCao() {
        try{
            WebRowSet wrs1 = BaoCaoThangController.baoCaoThang_GetById(this.MaBC);
            wrs1.next();
            this.lbDoanhThu.setText(Format_Price(wrs1.getString("DoanhThu").replace(".0000", "")));
            this.lbDoanhThuTemp.setText(wrs1.getString("DoanhThu").replace(".0000", ""));
            this.lbTienDV.setText(Format_Price(wrs1.getString("TienDV").replace(".0000", "")));
            this.lbTienDVTemp.setText(wrs1.getString("TienDV").replace(".0000", ""));
            this.lbTienPhong.setText(Format_Price(String.valueOf(Long.parseLong(this.lbDoanhThuTemp.getText())-Long.parseLong(this.lbTienDVTemp.getText()))));
            this.lbTienPhongTemp.setText(String.valueOf(Long.parseLong(this.lbDoanhThuTemp.getText())-Long.parseLong(this.lbTienDVTemp.getText())));
            WebRowSet wrs2 = CTBaoCaoThangController.ctBaoCaoThang_GetByTop("", "MaBC = '" +this.MaBC+ "'", "");
            DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
            model.getDataVector().removeAllElements();
            String[] tableColumnsName = {"STT","Mã Loại Phòng", "Tên Loại Phòng", "Tiền Phòng", "Tiền DV", "Doanh Thu", "Tỷ Lệ "};
            model.setColumnIdentifiers(tableColumnsName);
            Vector dataRow;
            while(wrs2.next())
            {
                dataRow = new Vector();
                dataRow.add(wrs2.getRow());
                dataRow.add("MLP"+wrs2.getObject("MaLoaiPhong"));
                WebRowSet wrs3 = LoaiPhongCotroller.loaiPhong_GetById(wrs2.getString("MaLoaiPhong"));
                wrs3.next();
                dataRow.add(wrs3.getObject("TenLoaiPhong"));
                dataRow.add(String.valueOf(Long.parseLong(wrs2.getObject("DoanhThu").toString().replace(".0000", ""))-Long.parseLong(wrs2.getObject("TienDV").toString().replace(".0000", ""))));
                dataRow.add(wrs2.getObject("TienDV").toString().replace(".0000", ""));
                dataRow.add(wrs2.getObject("DoanhThu").toString().replace(".0000", ""));
                DecimalFormat df=new DecimalFormat("0.000");
                df.setRoundingMode(RoundingMode.HALF_DOWN); 
                dataRow.add(df.format((Double.parseDouble(wrs2.getObject("DoanhThu").toString().replace(".0000", ""))/Double.parseDouble(wrs1.getObject("DoanhThu").toString().replace(".0000", "")))*100).replace(".000", ""));
                model.addRow(dataRow);
            }
            jtDoanhThuLoaiPhong.getColumnModel().getColumn(0).setPreferredWidth(10);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    
private void btnLapBaoCaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLapBaoCaoActionPerformed
// TODO add your handling code here:
    try{
        CTBaoCaoThangDTO ctbct = new CTBaoCaoThangDTO();
        BaoCaoThangDTO bct = new BaoCaoThangDTO();
        bct.setMaBC(null);
        bct.setThang(String.valueOf(this.mcThang.getMonth()+1));
        bct.setNam(String.valueOf(ycNam.getValue()));
        bct.setDoanhThu(this.lbDoanhThuTemp.getText());
        bct.setTienDV(this.lbTienDVTemp.getText());
        if(btnLapBaoCao.getText().equals("Lập báo cáo"))
        {
            if(BaoCaoThangController.baoCaoThang_Insert(bct))
            {
                WebRowSet wrs = BaoCaoThangController.baoCaoThang_GetByTop("1", "", "MaBC DESC");
                if(wrs.size()>0)
                {
                    wrs.next();
                    ctbct.setMaBC(wrs.getString("MaBC"));
                    for(int i=0; i< this.jtDoanhThuLoaiPhong.getRowCount(); i++)
                    {
                        ctbct.setMaLoaiPhong(this.jtDoanhThuLoaiPhong.getValueAt(i, 1).toString().replace("MLP", ""));
                        ctbct.setTienDV(this.jtDoanhThuLoaiPhong.getValueAt(i, 4).toString());
                        ctbct.setDoanhThu(this.jtDoanhThuLoaiPhong.getValueAt(i, 5).toString());
                        CTBaoCaoThangController.ctBaoCaoThang_Insert(ctbct);
                    }
                }
                JOptionPane.showMessageDialog(this, "Lập báo cáo thành công !!");
                this.btnLapBaoCao.setVisible(false);
                btnXoa.setVisible(true);
            }
        }
        else
        {
            if(JOptionPane.showConfirmDialog(this, "Bạn chắc chắn muốn cập nhật lại chứ ?", "Question",JOptionPane.YES_NO_OPTION)!=1)
            {
                bct.setMaBC(this.MaBC);
                ctbct.setMaBC(this.MaBC);
                if(BaoCaoThangController.baoCaoThang_Update(bct))
                {
                    for(int i=0; i< this.jtDoanhThuLoaiPhong.getRowCount(); i++)
                    {
                        ctbct.setMaLoaiPhong(this.jtDoanhThuLoaiPhong.getValueAt(i, 1).toString().replace("MLP", ""));
                        ctbct.setTienDV(this.jtDoanhThuLoaiPhong.getValueAt(i, 4).toString());
                        ctbct.setDoanhThu(this.jtDoanhThuLoaiPhong.getValueAt(i, 5).toString());
                        CTBaoCaoThangController.ctBaoCaoThang_Update(ctbct);
                    }
                    JOptionPane.showMessageDialog(this, "Cập nhật báo cáo thành công !!");
//                    this.btnLapBaoCao.setEnabled(false);
                    this.btnLapBaoCao.setVisible(false);
                }
            }
        }
    }
    catch(Exception e)
    {
    }
}//GEN-LAST:event_btnLapBaoCaoActionPerformed

private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
// TODO add your handling code here:
    try{
        if(JOptionPane.showConfirmDialog(this, "Bạn chắc chắn muốn xóa báo cáo chứ ?", "Question",JOptionPane.YES_NO_OPTION)!=1)
        {
            CTBaoCaoThangController.ctBaoCaoThang_Delete(this.MaBC);
            BaoCaoThangController.baoCaoThang_Delete(this.MaBC);
            this.lbTienDV.setText("");
            this.lbTienDVTemp.setText("");
            this.lbDoanhThu.setText("");
            this.lbDoanhThuTemp.setText("");
            this.lbTienPhong.setText("");
            this.lbTienPhongTemp.setText("");
            JOptionPane.showMessageDialog(this, "Xóa báo cáo thành công !!");
            this.btnXoa.setVisible(false);
            btnLapBaoCao.setVisible(true);
            btnPrint.setVisible(false);
            DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                    model.removeRow(i);
            }
        }
    }
    catch(Exception e)
    {
        
    }
}//GEN-LAST:event_btnXoaActionPerformed

private void btnBCThangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBCThangActionPerformed
// TODO add your handling code here:
    this._TienDV = 0;
    this._TongTien = 0;
    this.TienDV = 0;
    this.TongTien = 0;
    i = 1;
    try{
        
        Date today=new Date(System.currentTimeMillis()); 
        if(this.ycNam.getValue()> (today.getYear()+1900) || (this.mcThang.getMonth()>today.getMonth() && this.ycNam.getValue() == today.getYear()))
        {
            JOptionPane.showMessageDialog(this, "Vượt quá thời gian hiện tại. Chọn lại thời gian !!");
            DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                    model.removeRow(i);
            }
            this.lbTienDV.setText("");
            this.lbTienDVTemp.setText("");
            this.lbTienPhong.setText("");
            this.lbTienPhongTemp.setText("");
            this.lbDoanhThu.setText("");
            this.lbDoanhThuTemp.setText("");
            this.btnLapBaoCao.setVisible(false);
            this.btnPrint.setVisible(false);
            this.btnXoa.setVisible(false);
            return;
        }
        else
        {
            if(this.KiemTraTrungBaoCaoThang())
            {
                if(JOptionPane.showConfirmDialog(this, "Báo cáo đã tồn tại. Bạn có muốn lấy báo cáo lên không?\n---========--- YES-Lấy lên | NO-Lập lại ---========---", "Question",JOptionPane.YES_NO_OPTION)!=1)
                {
                        DocBaoCao();
                        this.btnLapBaoCao.setVisible(false);
                        this.btnPrint.setVisible(true);
                        this.btnXoa.setVisible(true);
                        return;
                }
                else
                {
                    this.btnLapBaoCao.setText("Cập nhật báo cáo");
                    this.btnLapBaoCao.setVisible(true);
                    this.btnPrint.setVisible(true);
                    this.btnXoa.setVisible(false);
                }
            }
            if(this.TinhTyLe())
            {
                this.ThongTinBaoCao();
                this.lbTienDV.setText(Format_Price(String.valueOf(this._TienDV)));
                this.lbTienDVTemp.setText(String.valueOf(this._TienDV));
                this.lbTienPhong.setText(Format_Price(String.valueOf(this._TongTien-this._TienDV)));
                this.lbTienPhongTemp.setText(String.valueOf(this._TongTien-this._TienDV));
                this.lbDoanhThu.setText(Format_Price(String.valueOf(this._TongTien)));
                this.lbDoanhThuTemp.setText((String.valueOf(this._TongTien)));
                this.btnLapBaoCao.setVisible(true);
                this.btnPrint.setVisible(true);
                this.btnXoa.setVisible(false);
            }
            else
            {
                JOptionPane.showMessageDialog(this, "Không tồn tại hóa đơn trong tháng.\nXin vui lòng lập hóa đơn trước khi lập báo cáo.");
                DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
                for (int i = model.getRowCount() - 1; i >= 0; i--) {
                    model.removeRow(i);
                }
                this.lbTienDV.setText("");
                this.lbTienDVTemp.setText("");
                this.lbTienPhong.setText("");
                this.lbTienPhongTemp.setText("");
                this.lbDoanhThu.setText("");
                this.lbDoanhThuTemp.setText("");
                this.btnLapBaoCao.setVisible(false);
                this.btnPrint.setVisible(false);
                this.btnXoa.setVisible(false);
                return;
            }
        }
    }
    catch(Exception e){}
    
}//GEN-LAST:event_btnBCThangActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
// TODO add your handling code here:
    this.btnPrint.setVisible(false);
    this.btnLapBaoCao.setVisible(false);
    this.btnXoa.setVisible(false);
}//GEN-LAST:event_formWindowOpened

private WebRowSet KiemTraBCNam()
{
    Date today=new Date(System.currentTimeMillis()); 
    if(this.ycNam.getYear()> today.getYear()+1900)
    {
        JOptionPane.showMessageDialog(this, "Thời gian không hợp lệ");
        return null;
    }
    else
    {
        try{
            WebRowSet wrs = BaoCaoThangController.baoCaoThang_GetByTop("", "Nam = '" +this.ycNam.getYear()+ "'", "");
            if(wrs.size()>0)
                return wrs;
            else
            {
                JOptionPane.showMessageDialog(this, "Không có báo cáo tháng nào.\nBạn phải lập báo cáo tháng trước khi lập báo cáo năm.");
                return null;
            }
        }
        catch(Exception e)
        {
            return null;
        }
    }
}

private void btnBCNamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBCNamActionPerformed
// TODO add your handling code here:
    this._TongTien = 0;
    this._TienDV = 0;
    i = 2;
    try{
        WebRowSet wrs = this.KiemTraBCNam();
//        BCThangControl bctc = (BCThangControl)Naming.lookup("rmi://localhost:1308/BCThangControl");
        if(wrs != null)
        {
            DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
            model.getDataVector().removeAllElements();
            Vector dataRow;
            String[] tableColumnsName = {"STT","Tháng", "Tiền Phòng", "Tiền DV", "Doanh Thu", "Tỷ Lệ (%)"};
            model.setColumnIdentifiers(tableColumnsName);
            while(wrs.next())
            {
                this._TienDV += Long.parseLong(wrs.getObject("TienDV").toString().replace(".0000", ""));
                this._TongTien += Long.parseLong(wrs.getObject("DoanhThu").toString().replace(".0000", ""));
            }
            this.lbDoanhThu.setText(Format_Price(String.valueOf(this._TongTien)));
            this.lbDoanhThuTemp.setText(String.valueOf(this._TongTien));
            this.lbTienDV.setText(Format_Price(String.valueOf(this._TienDV)));
            this.lbTienDVTemp.setText(String.valueOf(this._TienDV));
            this.lbTienPhong.setText(Format_Price(String.valueOf(this._TongTien-this._TienDV)));
            this.lbTienPhongTemp.setText(String.valueOf(this._TongTien-this._TienDV));
            wrs = this.KiemTraBCNam();
            while(wrs.next())
            {
                dataRow = new Vector();
                dataRow.add(wrs.getRow());
                dataRow.add(wrs.getObject("Thang"));
//                dataRow.add(wrs.getObject(String.valueOf(Long.parseLong(wrs.getObject("DoanhThu").toString().replace(".0000", ""))- Long.parseLong(wrs.getObject("TienDV").toString().replace(".0000", "")))));
                dataRow.add(String.valueOf(Long.parseLong(wrs.getObject("DoanhThu").toString().replace(".0000", ""))-Long.parseLong(wrs.getObject("TienDV").toString().replace(".0000", ""))));
                dataRow.add(wrs.getObject("TienDV"));
                dataRow.add(wrs.getObject("DoanhThu"));
                DecimalFormat df=new DecimalFormat("0.000");
                df.setRoundingMode(RoundingMode.HALF_DOWN); 
                dataRow.add(df.format((Long.parseLong(wrs.getObject("DoanhThu").toString().replace(".0000", ""))/this._TongTien)*100).replace(".000", ""));
//                dataRow.add((String.valueOf((Long.parseLong(wrs.getObject("DoanhThu").toString().replace(".0000", ""))/this._TongTien)*100)));
                model.addRow(dataRow);
            }
            jtDoanhThuLoaiPhong.getColumnModel().getColumn(0).setPreferredWidth(10);
            this._TongTien = 0;
            this._TienDV = 0;
            this.btnPrint.setVisible(true);
            btnXoa.setVisible(false);
        }
    }
    catch(Exception e)
    {
        
    }
}//GEN-LAST:event_btnBCNamActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
    frmMain._main.setVisible(true);
    frmMain._main.setFocusable(true);
}//GEN-LAST:event_formWindowClosed

private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed

    try {
            // TODO add your handling code here:
            if(i ==  1)
            {
                String html = "";//<meta http-equiv=Content-Type content='text/html; charset=utf8'>";
               // html += "<RIGHT>CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</BR>----------Ðộc lập - Tự do - Hạnh phúc-----------</LEFT>";
                html += "<CENTER><h2>BÁO CÁO DOANH THU THEO THÁNG</h2>"; 
                html += "<b>Tháng : </b>" + String.valueOf(this.mcThang.getMonth()+1);
                html += "&nbsp;&nbsp;&nbsp<b>Năm : <i/b>" + ycNam.getYear() + "<BR>";
                html += "CHI TIẾT BÁO CÁO";
                String footer ="";
                footer += "<b>Tiền phòng : </b>" + lbTienPhongTemp.getText() + " VNĐ<br>";
                footer += "&nbsp;&nbsp;&nbsp<b>Tiền dịch vụ : </b>" + lbTienDVTemp.getText() + " VNĐ<br>";
                footer += "&nbsp;&nbsp;&nbsp<b>Tổng doanh thu : </b>" + lbDoanhThuTemp.getText() + " VNĐ<br>";
                BaoCao bc = new BaoCao();
                bc.baocao(jtDoanhThuLoaiPhong,html,footer,"400");
            }
            else if(i ==  2)
            {
                String html1 = "";//<meta http-equiv=Content-Type content='text/html; charset=utf8'>";
                //html1 += "<LEFT>CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</BR>----------Ðộc lập - Tự do - Hạnh phúc-----------</LEFT>";
                html1 += "<CENTER><h2>BÁO CÁO DOANH THU THEO NĂM</h2>"; 
                html1 += "&nbsp;&nbsp;&nbsp<b>Năm : </b>" + ycNam.getYear();
                
                String footer ="";
                footer += "<b>Tiền phòng : </b>" + lbTienPhongTemp.getText() + " VNĐ<br>";
                footer += "&nbsp;&nbsp;&nbsp<b>Tiền dịch vụ : </b>" + lbTienDVTemp.getText() + " VNĐ<br>";
                footer += "&nbsp;&nbsp;&nbsp<b>Tổng doanh thu : </b>" + lbDoanhThuTemp.getText() + " VNĐ<br>";
                BaoCao bc = new BaoCao();
                bc.baocao(jtDoanhThuLoaiPhong,html1,footer,"400");
            }
        } catch (Exception ex) {
            Logger.getLogger(frmBaoCao.class.getName()).log(Level.SEVERE, null, ex);
        }

    // TODO add your handling code here:
}//GEN-LAST:event_btnPrintActionPerformed

    private boolean KiemTraTrungBaoCaoThang()
    {
        try{
            WebRowSet wrs = BaoCaoThangController.baoCaoThang_GetByTop("", "Thang = '" +String.valueOf(this.mcThang.getMonth()+1)+ "' AND Nam = '" +String.valueOf(this.ycNam.getValue())+ "'", "");
            if(wrs.size()>0)
            {
                wrs.next();
                this.MaBC = wrs.getString("MaBC");
                return true;
            }
            else
                return false;
        }
        catch(Exception e)
        {
            return false;
        }
    }
    private boolean TinhTyLe()
    {
        this._TongTien = 0;
        this._TienDV = 0;
        try{
            WebRowSet wrs = HoaDonController.hoaDon_GetByTop("", " year(NgayLap)= '"+String.valueOf(this.ycNam.getValue())+ "' AND month(NgayLap)= '"+String.valueOf(this.mcThang.getMonth()+1)+"'", "");
            if(wrs.size()>0)
            {
                while(wrs.next())
                {
                    this._TongTien += Long.parseLong(wrs.getObject("TongTien").toString().replace(".0000", ""));
                    this._TienDV += Long.parseLong(wrs.getObject("TienDV").toString().replace(".0000", ""));
                }
                return true;
            }
            return false;
        }
        catch(Exception e)
        {
            return false;
        }
    }
    private void ThongTinBaoCao()
    {
        try{
            DefaultTableModel model = (DefaultTableModel) this.jtDoanhThuLoaiPhong.getModel();
            model.getDataVector().removeAllElements();
            String[] tableColumnsName = {"STT","Mã Loại Phòng", "Tên Loại Phòng", "Tiền Phòng", "Tiền DV", "Doanh Thu", "Tỷ Lệ (%)"};
            model.setColumnIdentifiers(tableColumnsName);
            Vector dataRow;
            WebRowSet wrs1 = LoaiPhongCotroller.loaiPhong_GetByAll();
            if(wrs1.size()>0)
            {
                while(wrs1.next())
                {
                    dataRow = new Vector();
                    dataRow.add(wrs1.getRow());
                    dataRow.add("MLP"+wrs1.getString("MaLoaiPhong"));
                    dataRow.add(wrs1.getString("TenLoaiPhong"));
                    WebRowSet wrs2 = PhongController.phong_GetByTop("", " MaLoaiPhong = '" +wrs1.getString("MaLoaiPhong")+ "'", "");
                    if(wrs2.size()>0)
                    {
                        while(wrs2.next())
                        {
                            WebRowSet wrs3= PhieuThueController.phieuThue_GetByTop("", "MaPhong = '" +wrs2.getString("MaPhong")+ "'", "");
                            if(wrs3.size()>0)
                            {
                                while(wrs3.next())
                                {
                                    WebRowSet wrs4 = HoaDonController.hoaDon_GetByTop("", "MaPhieuThue = '" +wrs3.getString("MaPhieuThue")+ "' AND year(NgayLap)= '" +String.valueOf(this.ycNam.getValue())+ "' AND month(NgayLap)= '" +String.valueOf(this.mcThang.getMonth()+1) + "'", "");
                                    if(wrs4.size()>0)
                                    {
                                        while(wrs4.next())
                                        {
                                            TongTien += Long.parseLong(wrs4.getString("TongTien").replace(".0000", "")); 
                                            TienDV += Long.parseLong(wrs4.getString("TienDV").replace(".0000", ""));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    dataRow.add(this.TongTien - this.TienDV);
                    dataRow.add(this.TienDV);
                    dataRow.add(this.TongTien);
                    DecimalFormat df=new DecimalFormat("0.000");
                    df.setRoundingMode(RoundingMode.HALF_DOWN); 
                    dataRow.add(df.format(((double)this.TongTien/(double)this._TongTien)*100).replace(".000", ""));
                    model.addRow(dataRow);
                    this.TongTien = 0;
                    this.TienDV = 0;
                }
                jtDoanhThuLoaiPhong.getColumnModel().getColumn(0).setPreferredWidth(10);
            }
        }
        catch(Exception e)
        {
        }
    }

    ///<editor-fold defaultstate="collapsed" desc=" Format_Price ">
    private String Format_Price(String Price)
        {
            if ("0".equals(Price))
            {
                return "0 VNĐ";
            }
            else
                Price = Price.replace(".0", "");
            Price = Price.replace(",", "");
            String tmp = "";
            while (Price.length() > 3)
            {
                tmp = "." + Price.substring(Price.length() - 3) + tmp;
                Price = Price.substring(0, Price.length() - 3);
            }
            tmp = Price + tmp + " VNĐ";
            return tmp;
        }
    //</editor-fold>
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmBaoCao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmBaoCao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmBaoCao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmBaoCao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmBaoCao().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBCNam;
    private javax.swing.JButton btnBCThang;
    private javax.swing.JButton btnLapBaoCao;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnXoa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTable jtDoanhThuLoaiPhong;
    private javax.swing.JLabel lbDoanhThu;
    private javax.swing.JLabel lbDoanhThuTemp;
    private javax.swing.JLabel lbTienDV;
    private javax.swing.JLabel lbTienDVTemp;
    private javax.swing.JLabel lbTienPhong;
    private javax.swing.JLabel lbTienPhongTemp;
    private com.toedter.calendar.JMonthChooser mcThang;
    private com.toedter.calendar.JYearChooser ycNam;
    // End of variables declaration//GEN-END:variables
}
